import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;

import java.io.IOException;

/**
 * @Author ufo
 * @Description TODO
 * @Date 2021/1/11 16:28
 * @Version 1.0
 */
@Slf4j
public class DataWatch implements Watcher,Runnable{

    String hostPart = "127.0.0.1:2181";
    String zooDataPath = "/parentnull";
    byte[] zooData = null;
    ZooKeeper zk;

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        DataWatch dataWatch = new DataWatch();
        dataWatch.printData();
        dataWatch.run();
    }

    public DataWatch() {
        try {
            zk = new ZooKeeper(hostPart,2000,this);
            if (zk.exists(zooDataPath,this) == null){
                zk.create(zooDataPath,"".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);

            }
        } catch (IOException | KeeperException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void printData() throws KeeperException, InterruptedException {
        zooData = zk.getData(zooDataPath,this,null);
        String zString = new String(zooData);
        System.out.println("\nCurrent Data: "+zooDataPath+"   "+zString);

    }



    @Override
    public void run() {
        try {
            synchronized (this){
                while (true){
                    wait();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }

    @Override
    public void process(WatchedEvent event) {
        System.out.printf("\nReceive Events: %s",event.toString());
        // 我们只处理数据改变的Node
        if (event.getType() == Event.EventType.NodeDataChanged){
            try {
                printData();
            } catch (KeeperException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
